package com.nanjia.boot.myflow.order.service.impl;

import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.nanjia.boot.common.enums.OrderStatusEnum;
import com.nanjia.boot.common.enums.OrderTypeEnum;
import com.nanjia.boot.common.exception.BusinessException;
import com.nanjia.boot.core.security.util.SecurityUtils;
import com.nanjia.boot.myflow.deliveryaddressflow.model.entity.DeliveryAddressFlow;
import com.nanjia.boot.myflow.order.converter.OrderConverter;
import com.nanjia.boot.myflow.order.dto.OrderDTO;
import com.nanjia.boot.myflow.order.mapper.OrderMapper;
import com.nanjia.boot.myflow.order.model.entity.Order;
import com.nanjia.boot.myflow.order.model.form.OrderForm;
import com.nanjia.boot.myflow.order.model.query.OrderQuery;
import com.nanjia.boot.myflow.order.model.vo.OrderVO;
import com.nanjia.boot.myflow.order.service.OrderService;
import lombok.RequiredArgsConstructor;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;

/**
 * 订单主服务实现类
 *
 * @author 周洋
 * @since 2025-07-11 11:49
 */
@Service
@RequiredArgsConstructor
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order> implements OrderService {

    private final OrderConverter orderConverter;

    private final OrderMapper orderMapper;


    /**
     * 获取订单主分页列表
     *
     * @param queryParams 查询参数
     * @return {@link IPage<OrderVO>} 订单主分页列表
     */
    @Override
    public IPage<OrderVO> getOrderPage(OrderQuery queryParams) {
        Page<OrderVO> pageVO = this.baseMapper.getOrderPage(
                new Page<>(queryParams.getPageNum(), queryParams.getPageSize()),
                queryParams
        );
        return pageVO;
    }

    /**
     * 获取订单主表单数据
     *
     * @param id 订单主ID
     * @return 订单主表单数据
     */
    @Override
    public OrderForm getOrderFormData(Long id) {
        Order entity = this.getById(id);
        return orderConverter.toForm(entity);
    }

    /**
     * 新增订单主
     *
     * @param formData 订单主表单对象
     * @return 是否新增成功
     */
    @Override
    public boolean saveOrder(OrderForm formData) {
        Order entity = orderConverter.toEntity(formData);
        return this.save(entity);
    }

    /**
     * 更新订单主
     *
     * @param id       订单主ID
     * @param formData 订单主表单对象
     * @return 是否修改成功
     */
    @Override
    public boolean updateOrder(Long id, OrderForm formData) {
        Order entity = orderConverter.toEntity(formData);
        entity.setId(id);
        return this.updateById(entity);
    }

    /**
     * 删除订单主
     *
     * @param ids 订单主ID，多个以英文逗号(,)分割
     * @return 是否删除成功
     */
    @Override
    public boolean deleteOrders(String ids) {
        Assert.isTrue(StrUtil.isNotBlank(ids), "删除的订单主数据为空");
        // 逻辑删除
        List<Long> idList = Arrays.stream(ids.split(","))
                .map(Long::parseLong)
                .toList();
        return this.removeByIds(idList);
    }

    @Override
    public OrderForm getCartOrderFormByUser(String ipAddr) {

        Order cart = createCart(SecurityUtils.getUserId(), ipAddr);
        OrderForm form = orderConverter.toForm(cart);
        return form;
    }

    private Order createCart(Long userId, String ipAddr) {
        List<Order> list = this.list(new LambdaQueryWrapper<Order>().eq(Order::getUserId, SecurityUtils.getUserId()).eq(Order::getStatus, OrderStatusEnum.CART.getValue()).orderByDesc(Order::getId));

        //购物车订单只有一个

        if (CollectionUtils.isEmpty(list)) {
            Order order = new Order();
            order.setOrderSn(userId + "00001");
            order.setUserId(userId);
            order.setStatus(OrderStatusEnum.CART.getValue());
            order.setCreateIp(ipAddr);
            order.setUpdateIp(ipAddr);
            order.setCreateBy(String.valueOf(userId));
            order.setUpdateBy(String.valueOf(userId));
            order.setCreateTime(LocalDateTime.now());
            order.setUpdateTime(LocalDateTime.now());
            order.setTotalAmount(BigDecimal.ZERO);
            order.setDaf0Id(1L);
            order.setDaf1Id(1L);
            this.save(order);
            return order;
        }

        return list.get(0);
    }

    @Override
    @Transactional(rollbackFor = BusinessException.class)
    public Order createOrder(OrderForm formData, String ipAddr, List<DeliveryAddressFlow> deliveryAddressFlows) {
        if (formData == null || (CollectionUtils.isEmpty(formData.getOrderItems()) && formData.getSkuId() == null) || CollectionUtils.isEmpty(formData.getDeliveryAddresses())) {
            return null;
        }
        //先创建订单
//        long count = this.count(new LambdaQueryWrapper<Order>().eq(Order::getUserId, SecurityUtils.getUserId()));
        Order order = new Order();
        order.setUserId(SecurityUtils.getUserId());
        order.setOrderSn("XS" + SecurityUtils.getUserId() + UUID.randomUUID().toString().replace("-", "").substring(0, 8));
        order.setStatus(OrderStatusEnum.Status1.getValue());
        order.setCreateIp(ipAddr);
        order.setUpdateIp(ipAddr);
        order.setCreateBy(SecurityUtils.getUserStrId());
        order.setUpdateBy(JSONUtil.toJsonStr(SecurityUtils.getUserId()));
        order.setCreateTime(LocalDateTime.now());
        order.setUpdateTime(LocalDateTime.now());
        order.setTotalAmount(formData.getTotalAmount());
        order.setRemark(formData.getRemark());
        order.setOrderType(OrderTypeEnum.SELL.getValue());
        deliveryAddressFlows.forEach(flow -> {
            if (flow.getDeliveryType() == 0) {
                order.setDaf0Id(flow.getId());
            } else {
                order.setDaf1Id(flow.getId());
            }
        });
        boolean save = this.save(order);
        if (save) {
            return order;
        }


        return null;
    }

    @Override
    public List<OrderDTO> orderDTOList(OrderQuery queryParams) {


        return orderMapper.orderDTOList(queryParams);
    }
}
